﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace DbfTools
{
	public class DbfRows<T> : IEnumerable<T>, IDisposable
		where T : ITableSavable<T>, new()
	{
		DbfRecords Records;
		internal DbfRows(DBFile dbf)
		{
			Records = new DbfRecords(dbf);
		}

		public T this[int index]
		{
			get
			{
				return new T().ParseRow(Records[index].GetItems());
			}
		}
		public int Count
		{
			get { return Records.Count; }
		}

		#region IEnumerable<T> Members
		public IEnumerator<T> GetEnumerator()
		{
			return new DbfEnumerator(this);
		}
		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return new DbfEnumerator(this);
		}
		class DbfEnumerator : IEnumerator<T>
		{
			System.Collections.IEnumerator Enumerator;
			public DbfEnumerator(DbfRows<T> rows)
			{
				Enumerator = rows.Records.GetEnumerator();
			}

			#region IEnumerator<T> Members
			T GetCurrent()
			{
				return new T().ParseRow((Enumerator.Current as DbfRecord).GetItems());
			}
			public T Current
			{
				get { return GetCurrent(); }
			}
			#endregion

			#region IDisposable Members
			public void Dispose(){}
			#endregion

			#region IEnumerator Members
			object System.Collections.IEnumerator.Current
			{
				get { return GetCurrent(); }
			}
			public bool MoveNext()
			{
				return Enumerator.MoveNext();
			}
			public void Reset()
			{
				Enumerator.Reset();
			}
			#endregion
		}
		#endregion

		#region IDisposable Members
		public void Dispose()
		{
			Records.DbfFile.Dispose();
			Records = null;
		}
		#endregion
	}
	public class SimpleRow : ITableSavable<SimpleRow>
	{
		public SimpleRow() { }

		object[] Items = new object[100];
		public object this[int index]
		{
			get { return Items[index]; }
		}
		public int FieldsCount { get { return Items.Length; } }
		#region ITableSavable<SimpleRow> Members
		public Type[] GetColumnTypes()
		{
			return Enumerable.Repeat(typeof(object), FieldsCount).ToArray();
		}
		public object[] GetRowArray()
		{
			return Items;
		}
		public SimpleRow ParseRow(object[] row)
		{
			Items = row;
			return this;
		}
		#endregion
	}
}
